import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { createSetPageErrorAction } from '@/redux/actions/pageError'
import { Button } from 'antd-mobile'
import Avatar from '@/components/Avatar'
import ResponsiveImage from '@/components/ResponsiveImage'
import ArticleContent from './content'
import ArticleRecommend from './recommend'
import ArticleComment from '@/components/Comment'
import { articleApi } from '@/api'
import { dateFormat, formatNumber } from '@/utils'
import css from './index.module.scss'
class Article extends PureComponent {    
    state = {
        info: null,
        articleContent: null,
        formatContent: null,
        recommend: null,
        comments: null,
        videos: null
    }
    
    get articleId() {
        const { match: { params: { id } } } = this.props
        return id
    }

    get banner() {
        return this.state?.info?.banner_url ?? ''
    }

    get type() {
        return this.state?.articleContent?.type ?? ''
    }

    get time() {
        return this.state?.articleContent?.timestamp ?? ''
    }

    get videoIds() {
        return this.state?.articleContent?.videoIds ?? []
    }

    get tags() {
        return this.state?.articleContent?.tags ?? []
    }

    get view() {
        return this.state?.info?.stats?.view ?? 0
    }

    get author() {
        return this.state?.recommend?.author ?? null        
    }

    initData = async () => {
        try {
            await this.getInfo()
            await this.getContent()
            await this.getContentVideos()
            await this.getRecommend()        
            await this.getComments()
        } catch (error) {
            this.props.setPageError(true)
        }
    }

    getInfo = async () => {
        try {
            const { data } = await articleApi.getInfo({
                id: this.articleId
            })
            if (data) {
                this.setState({
                    info: data
                })
            }
        } catch (error) {
            throw new Error(error)
        }
    }

    getContent = async () => {
        try {
            const { data } = await articleApi.getContent({
                id: this.articleId
            })
            if (data) {
                this.setState({
                    articleContent: data,
                    formatContent: data.content
                })
            }
        } catch (error) {
            
        }
    }

    getContentVideos = async () => {
        try {
            if (this.videoIds.length === 0) {
                return
            }
            const { data } = await articleApi.getContentVideo({
                id: this.articleId,
                ids: this.videoIds.join(',')
            })
            if (data) {
                const { articleContent } = this.state
                let fcontent = ''
                this.setState({
                    videos: data
                })
                for (const value of this.videoIds.values()) {
                    const ids = value.split(',')
                    const htms = []
                    for (const id of ids.values()) {
                        htms.push(this.parseVideo(data[id]))
                    }

                    fcontent = articleContent.content.replace(`<i data-ids="${value}"></i>`, htms.join(''))
                }
                this.setState({
                    formatContent: fcontent
                })
            }
        } catch (error) {
            
        }
    }

    parseVideo = (video) => {
        const html = `
            <div class="video-item">
                <a class="video-link" data-bvid="${video.bvid}"></a>
                <div class="video-cover">
                    <img class="img" src="${video.pic}@300w_188h" />
                </div>
                <div class="video-info">
                    <div class="video-title">${video.title}</div>
                    <div class="video-author">
                        <i class="fa fa-up-zhu"></i>
                        <span class="name">${video.owner.name}</span>
                    </div>
                </div>
            </div>
        `
        return html
    }

    getRecommend = async () => {
        try {
            const { data } = await articleApi.getRecommend({
                aid: this.articleId
            })
            if (data) {
                this.setState({
                    recommend: data
                })
            }
        } catch (error) {
            
        }
    }

    getComments = async () => {
        try {
            const { data } = await articleApi.getComments({
                oid: this.articleId
            })
            if (data) {
                this.setState({
                    comments: data.replies
                })
            }
        } catch (error) {
            
        }
    }

    handleSpace = () => {
        this.props.history.push(`/space/${this.author.mid}`)
    }

    componentDidMount() {
        this.initData()
    }

    componentDidUpdate(prevProps) {
        const prevId = prevProps.match.params.id
        if (prevId !== this.articleId) {
            this.initData()
        }
    }

    render() {
        const { info, formatContent, articleContent, recommend, comments } = this.state
        const author = this.author
        return (
            <>
                {
                    info && <>
                        { this.banner && <ResponsiveImage className={css["banner"]} src={this.banner} size="@480w_270h" webp={false} /> }
                        <div className={css["title-wrap"]}>
                            <h1 className="title">{ info.title }</h1>
                            <div className="info">
                                { this.type && <span className="type">{ this.type }</span> }
                                { this.time && <span className="time">{ dateFormat(new Date(this.time*1000), 'MM-dd') }</span> }
                                { this.view && <span className="view">{ formatNumber(this.view) }阅读</span> }
                            </div>
                        </div>
                        {
                            author && <div className={css["author-wrap"]} onClick={this.handleSpace}>
                                <Avatar
                                    className="face"
                                    size="small"
                                    src={author.face}
                                    vip={author.vip.vipStatus}
                                    official={author.official_verify}
                                />
                                <span className="name">{ author.name }</span>
                                <Button className="follow" size="small" disabled={author.is_followed}>{author.is_followed ? '已关注' : '关注'}</Button>                                
                            </div>
                        }
                        { articleContent && <ArticleContent info={info} content={formatContent} tags={articleContent.tags} /> }
                        { recommend && <ArticleRecommend list={recommend.articles} /> }
                        { comments && <ArticleComment className={css["comment-wrap"]} comments={comments}/>}
                    </>
                }                
            </>
        )       
    }
}

export default connect(
    null,
    {
      setPageError: createSetPageErrorAction
    }
)(Article)